﻿using DDD.Core.Exceptions.Bussines;
using DDD.Core.Result;
using DDD.Core.Result.Enum;
using Microsoft.AspNetCore.Http;
using Microsoft.Extensions.Logging;
using Newtonsoft.Json;

namespace DDD.Core.Middlewares
{
    [Obsolete]
    public class ExceptionMiddleware
    {
        private readonly RequestDelegate _next;
        private readonly ILogger<ExceptionMiddleware> _logger;

        public ExceptionMiddleware(RequestDelegate next, ILogger<ExceptionMiddleware> logger)
        {
            _next = next;
            _logger = logger;
        }

        public async Task Invoke(HttpContext context)
        {
            try
            {
                await _next(context);
            }
            catch (Exception ex)
            {
                if (ex is Exceptions.SystemException)
                {
                    _logger.LogError(new EventId(Guid.NewGuid().GetHashCode()), ex, $"时间：{DateTime.Now}，系统异常。");

                    var errorResult = new ApiResult(BusinessEnum.SystemError, "系统异常");

                    await context.Response.WriteAsync(JsonConvert.SerializeObject(errorResult));
                }
                else
                {
                    string message = string.Empty;

                    if (ex is VaildateException)
                    {
                        var vaildateEx = ex as VaildateException;
                        message = string.Join("。", vaildateEx.Errors.Select(c => $"{c.Property}:{c.Error}"));
                    }
                    else
                    {
                        message = ex.Message;
                    }

                    _logger.LogError(new EventId(Guid.NewGuid().GetHashCode()), ex, $"时间：{DateTime.Now}，错误的请求：{message}");

                    var vaildateResult = new ApiResult(BusinessEnum.BadRequest, message);

                    await context.Response.WriteAsync(JsonConvert.SerializeObject(vaildateResult));
                }
            }
        }
    }
}
